package com.i2works.smartluolong.web.controller.common;


import com.i2works.smartluolong.utils.common.VerifyCodeUtil;
import com.i2works.smartluolong.utils.common.ZxingUtil;
import com.i2works.smartluolong.utils.redis.RedisSessionDAO;
import com.i2works.smartluolong.utils.web.HtmlConstant;
import com.i2works.smartluolong.web.utils.BaseModule;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;


/**
 * 公共控制器
 *
 * @author Liu Yutao
 * @className commonController
 * @email koal@vip.qq.com
 * @date 2016/10/20 12:57
 */


@Controller
public class CommonController extends BaseModule {

    @Autowired
    private RedisSessionDAO redisSessionDAO;


    /**
     * 二维码生成
     */
    @GetMapping("/common/qrCode")
    public void qrCode(@RequestParam(value = "content", required = false) String content, HttpServletResponse response) {
        try {
            BufferedImage image = ZxingUtil.image(content, null, false);
            response.setContentType("image/jpeg");
            ServletOutputStream outputStream = response.getOutputStream();
            ImageIO.write(image, "jpeg", outputStream);
            outputStream.close();
        } catch (Exception e) {
            logger.error("二维码生成异常:" + e.getMessage());
        }

    }


    /**
     * 验证码生成
     */
    @GetMapping("/common/verifyCode")
    public void verifyCode(HttpServletRequest request, HttpServletResponse response) {
        try {
            String textCode = VerifyCodeUtil.generateTextCode(4);
            Font font = new Font("Times New Roman", Font.BOLD + Font.ITALIC, 0);
            BufferedImage verifyImage = VerifyCodeUtil.generateImageCode(textCode, font, 190, 50, 3, true, null, null, null);
            // 将四位数字的验证码保存到redis中。
            redisSessionDAO.set(request.getSession(true).getId(), textCode, 300L);
            // 禁止图像缓存。
            response.setContentType("image/png");
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            response.setDateHeader("Last-Modified", System.currentTimeMillis());
            response.setDateHeader("Date", System.currentTimeMillis());
            // 将图像输出到Servlet输出流中。
            ServletOutputStream sos = response.getOutputStream();
            ImageIO.write(verifyImage, "png", sos);
            sos.close();
        } catch (Exception e) {
            logger.error("验证码异常:" + e.getMessage());
        }
    }

    /**
     * 验证码检测
     * @return Boolean 存在返回false,不存在返回true
     */
    @PostMapping("/common/checkVerify")
    @ResponseBody
    public Boolean checkVerify(@RequestParam("imgCode") String imgCode, HttpServletRequest request) {
        //非空验证
        if (StringUtils.isBlank(imgCode)) {
            return false;
        }
        //获取验证码ID
        String id = request.getSession(true).getId();
        //获取imgCode
        String redisImgCode = String.valueOf(redisSessionDAO.get(id));
        if (StringUtils.isNotBlank(redisImgCode)) {
            if (redisImgCode.equalsIgnoreCase(imgCode)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 网站信息页面
     */
    @GetMapping("/info/{infoPage}")
    public String feedback(@PathVariable String infoPage, HttpServletRequest request) {
        return "info/" + infoPage.toLowerCase();
    }

    /**
     * 错误页面
     */
    @GetMapping(value = {"/error", "/error/error", "/common/error", "/400", "/403", "/404", "/500", "/503"})
    public String error(HttpServletRequest request, HttpServletResponse response) {
        response.setStatus(404);
        return "common/error";
    }

    /**
     * 消息页面
     */
    @GetMapping(HtmlConstant.MESSAGE_HTML)
    public String message(HttpServletRequest request) {
        return "/common/message";
    }

}